<template>
  <div class="container">
    <div class="background">
      <movable-area class="problem-plane" >
        <movable-view  v-if="displayCard" class="card" :x="x" :y="y" direction="all" @touchstart="onTouchstart" @touchmove="onTouchmove" @touchend="onTouchend">{{word}}</movable-view>
        <!-- 显示答案的区域,没答题前隐藏，但存在，只是看不见 -->
        <div class="correct-answer"  :style="displayAnswer">
          <!--              显示答案区域-->
          <p class="borderTop">正确答案</p>
          <p class="borderCorrectMid">{{correctSentence}}</p>
          <p v-if="isCorrect === 1" class="borderYourMidBlue">你的答案</p>
          <p v-else class="borderYourMidRed">你的答案</p>
          <p v-if="isCorrect === 1" class="borderBotBlue">{{yourSentence}}</p>
          <p v-else class="borderBotRed">{{yourSentence}}</p>
        </div>
        <div class="words">
          <!--          <div class="word" v-for="(word , index) in answer" :key="index"  id="word" @click="an">{{word}}</div>-->
          <div v-for="(word , index) in answer" :key="index"  id="word" @click="an">
            <div v-if="isCorrect === -1">
              <div class="word">{{word}}</div>
            </div>
            <div v-else-if="isCorrect === 0 && index === yourAnswer">
              <div class="wordRed">{{word}}</div>
            </div>
            <div v-else-if="isCorrect ===1 && index === yourAnswer">
              <div class="wordGreen">{{word}}</div>
            </div>
            <div v-else>
              <div class="word">{{word}}</div>
            </div>
          </div>
        </div>
      </movable-area>

      <div class="button-plane">
        <button class="buttonStyle" @click="backToIndexPage">主界面</button>
        <button class="buttonStyle" @click="nextProblem">下一题</button>
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    data () {
      return {
        serverIP: '',
        mpOpenId: '',
        level: '',
        // 回答问题的相关数据
        answerIndex: 0, // 正确的答案index
        yourAnswer: 0, // 用户的答案index
        word: '', // 移动的单词
        problem: '', // 需要回答的题目
        answer: '', // 回答之后的句子
        problems: '', // 从后台获取的问题集
        currentProblem: 0, // 当前的问题index
        numberOfcorrect: 0, // 本次正确回答的题数
        // 卡片的设置，为了方便硬编码了，可以更改
        x: '140',
        y: '40',
        displayAnswer: 'visibility:hidden',
        displayCard: true,
        // 实现稳定拖动,计算开始时，手指在组件card内的相对坐标
        xInside: '',
        yInside: '',
        // 答题区域单词的坐标，数组包含所有的单词，其中y坐标是集合。
        xOfWords: '',
        yOfWords: '',
        isCorrect: -1
      }
    },

    computed: {
      correctSentence () {
        if (this.problem === '') return ''
        return this.problem.join(' ')
      },
      yourSentence () {
        if (this.answer === '') return ''
        return this.answer.join(' ')
      }
    },

    onLoad () {
      // 从全局缓存获取服务器IP
      this.serverIP = wx.getStorageSync('serverIP')
      // 获取难度和用户信息
      this.level = wx.getStorageSync('level')
      this.mpOpenId = wx.getStorageSync('mpOpenId')
      // wx.request不支持同步，变相实现同步。把所有操作写入request中
      const self = this
      wx.request({
        url: this.serverIP + '/problem/wx?grade=' + this.level,
        header: { 'Content-Type': 'application/json' },
        method: 'GET',
        success (res) {
          self.problems = res.data.params
          console.log('第一次获取题目成功')
          self.beforeAnswer()
        },
        fail () {
          console.log('获取题目失败')
        }
      })
    },

    onUnload () {
      // 提交成绩
      wx.request({
        url: this.serverIP + '/score',
        header: { 'Content-Type': 'application/json' },
        method: 'POST',
        data: {
          'score': this.numberOfcorrect,
          'mpOpenId': this.mpOpenId
        },
        success (res) {
          console.log('提交成绩成功')
          console.log(res)
        },
        fail (res) {
          console.log('提交成绩失败')
          console.log(res)
        }
      })
      // 清除数据和恢复界面
      this.displayAnswer = 'visibility:hidden'
      this.displayCard = true
      this.beforeAnswer()
      this.currentProblem = 0
      this.numberOfcorrect = 0
      this.isCorrect = -1
    },
    methods: {
      getProblemsFromServer () {
        // 从服务器获取题目
        const self = this
        wx.request({
          url: this.serverIP + '/problem/wx?grade=' + this.level,
          header: { 'Content-Type': 'application/json' },
          method: 'GET',
          success (res) {
            self.problems = res.data.params
            console.log('获取题目成功')
          },
          fail () {
            console.log('获取题目失败')
          }
        })
      },
      /** 核心函数
       * 回答问题前的操作
       * 通过计算x，y的差距来获得用户回答
       */

      beforeAnswer () {
        // 卡片位置复原
        this.cardReturn()
        // 更新数据，包括回答的问题（problem），移动的单词（word），正确的index（answerIndex），用户的回答
        this.setProblem()
      },

      setProblem (problem) {
        // 根据currenProblem更新数据
        this.answerIndex = this.problems.indexes[this.currentProblem]
        this.problem = this.problems.problemes[this.currentProblem].problem.trim().split(' ')
        this.word = this.problem[this.answerIndex]
        this.yourAnswer = 0
        // 将整个问题复制到回答，显示在答题区域，进而保留原始问题
        this.answer = this.problem.slice()
        this.answer.splice(this.answerIndex, 1)
      },

      countIndex () {
        // 计算手指的坐标
        var fingerX = this.x + this.xInside
        var fingerY = this.y + this.yInside
        var finalIndex = 0
        // 先计算插入在第几行，然后更新索引到这一行的开头
        var line = 0
        while (line < this.yOfWords.length && fingerY > this.yOfWords[line]) {
          line++
        }
        line--
        while (line > 0) {
          finalIndex++
          if (this.xOfWords[finalIndex] > this.xOfWords[finalIndex + 1]) {
            line--
            finalIndex++
          }
        }
        // 计算插入在这行的第几个
        while (fingerX > this.xOfWords[finalIndex] && finalIndex < this.xOfWords.length && this.xOfWords[finalIndex] < this.xOfWords[finalIndex + 1]) {
          finalIndex++
        }
        if (fingerX > this.xOfWords[this.xOfWords.length - 1] || this.xOfWords[finalIndex] > this.xOfWords[finalIndex + 1]) finalIndex++
        return finalIndex
      },

      afterAnswer () {
        // 隐藏卡片，显示答案区域
        this.displayAnswer = 'visibility:visible'
        this.displayCard = false
        // 判断答题情况,累积得分
        if (this.answerIndex === this.yourAnswer) {
          this.numberOfcorrect++
          this.isCorrect = 1
        } else this.isCorrect = 0
        // 当前题目index切换到下一题。如果没有题目，先向服务器获取新的题目集
        this.currentProblem += 1
        if (this.currentProblem > this.problems.problemes.length) {
          this.currentProblem = 0
          this.getProblemsFromServer()
        }
      },

      /** 卡片的移动监听，包括点击，移动，释放 */
      onTouchstart (res) {
        this.xInside = res.clientX - this.x
        this.yInside = res.clientY - this.y
        // 获取所有的word组件的坐标
        const self = this
        wx.createSelectorQuery().selectAll('#word').boundingClientRect(function (rects) {
          var x = []
          var y = []
          rects.forEach(function (rect) {
            x.push(rect.left)
            if (y.indexOf(rect.top) === -1) y.push(rect.top)
          })
          self.xOfWords = x
          self.yOfWords = y
        }).exec()
        // 获取最下面组件的坐标，计算答题区域。还没实现。不想实现了。看情况
      },
      onTouchmove (res) {
        // 实现卡片随着手指移动
        this.x = res.clientX - this.xInside
        this.y = res.clientY - this.yInside
        // 检测是否进入答题区域，是则生产对应的空白块，否则不产生。以第一行的单词的y坐标作为判断坐标。坐标点用手指坐标的作为判断
        // 空白占位符也先不实现了，不是必要功能
        if (res.clientY >= (this.yOfWords[0])) {
          // console.log('进入答题区域')
        } else {
          // console.log('不在答题区域')
        }
      },
      onTouchend (res) {
        // 判断是否移动到答题区域。是则进入对错判断，否则将卡片返回到原处
        if ((this.y + this.yInside) >= this.yOfWords[0]) {
          this.yourAnswer = this.countIndex()
          this.answer.splice(this.yourAnswer, 0, this.word)
          console.log('答题成功')
          this.afterAnswer()
        } else {
          console.log('没有答题，卡片返回原处')
          this.cardReturn()
        }
      },
      // 卡片复原到原来的位置，使用了硬编码，可改
      cardReturn () {
        this.x = 140
        this.y = 40
      },
      // 绑定下一题按钮的点击事件
      nextProblem () {
        // 当前题目index切换到下一题。如果没有题目，先向服务器获取新的题目集
        this.isCorrect = -1
        this.currentProblem += 1
        if (this.currentProblem >= this.problems.problemes.length) {
          this.currentProblem = 0
          this.getProblemsFromServer()
        }
        // 显示卡片，隐藏答案界面
        this.displayAnswer = 'visibility:hidden'
        this.displayCard = true
        // 还有什么？
        this.beforeAnswer()
      },
      // 绑定主界面按钮的点击事件
      backToIndexPage () {
        wx.reLaunch({
          url: '/pages/index/main'
        })
      }
    }
  }
</script>

<style>
  /*page{height:100%}*/

  .container {
    display: flex;
    flex-direction: column;
  }

  .background {
    background-image:url('');
    width: 100%;
    height: 1334rpx;
    background-repeat: no-repeat;
  }

  .problem-plane {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 78%;
  }

  .card {
    text-align:center;
    height: auto;
    width: auto;
    top:150rpx;
    background: #f0b22e;
    padding:20rpx 30rpx;
    border-radius:25rpx;
    font-size:40rpx;
  }

  .correct-answer {
    display:flex;
    flex-direction:column;
    width:80%;
    font-size:40rpx;
  }

  .borderTop {
    background: #2abee9;
    border-top-left-radius: 50rpx;
    border-top-right-radius: 50rpx;
    padding: 20rpx 20rpx 0;
  }

  .borderCorrectMid {
    background: #2abee9;
    padding: 0 20rpx;
  }

  .borderYourMidBlue {
    background: #2abee9;
    padding: 0 20rpx;
  }

  .borderYourMidRed {
    background: red;
    padding: 0 20rpx;
  }

  .borderBotBlue {
    background: #2abee9;
    border-bottom-left-radius: 50rpx;
    border-bottom-right-radius: 50rpx;
    padding: 0 20rpx 20rpx;
  }

  .borderBotRed {
    background: red;
    border-bottom-left-radius: 50rpx;
    border-bottom-right-radius: 50rpx;
    padding: 0 20rpx 20rpx;
  }

  .words {
    display:flex;
    flex-direction:row;
    justify-content:flex-start;
    align-items:center;
    align-content:center;
    flex-wrap:wrap;
    margin:230rpx 50rpx;
  }

  .word {
    background:#ffffff;
    padding:20rpx 30rpx;
    margin:10rpx 20rpx;
    border-radius:25rpx;
    font-size:40rpx;
  }

  .wordRed {
    background:red;
    padding:20rpx 30rpx;
    margin:10rpx 20rpx;
    border-radius:25rpx;
    font-size:40rpx;
  }

  .wordGreen {
    background:#4de216;
    padding:20rpx 30rpx;
    margin:10rpx 20rpx;
    border-radius:25rpx;
    font-size:40rpx;
  }

  .button-plane {
    display: flex;
    flex-grow:1;
    align-items: center;
  }

  .buttonStyle {
    width: 250rpx;
    border-radius: 50rpx;
    color: #2abee9;
    font-size: 40rpx;
  }

</style>
